package be.gnx.fogo.application.ui;

import java.util.ResourceBundle;
import java.util.Set;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.widgets.Composite;

import be.gnx.fogo.application.model.Person;

public class FamilyCard extends Composite {

  private PersonGroup personGroup;
  private SpouseGroup spouseGroup;
  private ChildrenGroup childrenGroup;
  private InfoGroup infoGroup;

  private boolean asFamily = false;

  protected FamilyCard(Composite composite, int style, ResourceBundle resourceBundle) {
    super(composite, style);
    personGroup = new PersonGroup(this, SWT.NONE, resourceBundle);
    spouseGroup = new SpouseGroup(this, SWT.NONE, resourceBundle);
    childrenGroup = new ChildrenGroup(this, SWT.NONE, resourceBundle);
    infoGroup = new InfoGroup(this, SWT.NONE, resourceBundle);
    resize();

    addDisposeListener(new DisposeListener() {
      public void widgetDisposed(DisposeEvent disposeEvent) {
        FamilyCard.this.widgetDisposed(disposeEvent);
      }
    });

    addControlListener(new ControlAdapter() {
      public void controlResized(ControlEvent controlEvent) {
        FamilyCard.this.controlResized(controlEvent);
      }
    });

  }

  private void widgetDisposed(DisposeEvent disposeEvent) {
    // TODO;
  }

  private void controlResized(ControlEvent controlEvent) {
    resize();
  }

  private void resize() {
    personGroup.setBounds(0, 0, getSize().x / 2, getSize().y / 2);
    spouseGroup.setBounds(getSize().x / 2, 0, getSize().x / 2, getSize().y / 2);
    childrenGroup.setBounds(0, getSize().y / 2, getSize().x / 2, getSize().y / 2);
    infoGroup.setBounds(getSize().x / 2, getSize().y / 2, getSize().x / 2, getSize().y / 2);
  }

  protected void setAsFamily(boolean asFamily) {
    this.asFamily = asFamily;
    personGroup.setAsFamily(asFamily);
    spouseGroup.setAsFamily(asFamily);
    childrenGroup.setAsFamily(asFamily);
    infoGroup.setAsFamily(asFamily);
  }

  protected void setPerson(Person person) {
    if (asFamily) {
      Person father = person.getInhabitantFather();
      Person mother = person.getInhabitantMother();
      Set<Person> children = person.getInhabitantChildren();
      personGroup.setPerson(father);
      spouseGroup.setPerson(mother);
      childrenGroup.setPersonSet(children);
      infoGroup.setPerson(person);
    } else {
      personGroup.setPerson(person);
      spouseGroup.setPerson(person.getSpouse());
      childrenGroup.setPersonSet(person.getChildren());
      infoGroup.setPerson(person);
    }
  }

  protected void setPerson(Person person, boolean asFamily) {
    setAsFamily(asFamily);
    setPerson(person);
  }

}
